import {
	observable,
	action,
} from 'mobx';
import {
	WeaForm
} from 'comsMobx';

export default class FormStore {
	constructor(api) {
		this.api = api;
	}

	@observable form = new WeaForm();
	@observable loading = false;

	@action fetchForm = (params = {},callback) => {
		this.loading = true;
		this.form = new WeaForm();
		return this.api.fetchForm(params).then(datas => {
			const conditions = this.getCondition(datas);

			this.form.setCondition(conditions);
			this.loading = false;

			callback && callback(datas);
		})
	}

	validateForm = (form) => {
		return new Promise( (resolve,reject) => {
			form.validateForm().then(f => {
				if (f.isValid) {
					resolve(true);
				} else {
					f.showErrors();
					resolve(false);
				}
			})
		})
	}

	getCondition=(datas)=>{
		let c = [];
		Object.keys(datas).forEach(key=>{
			if (key.includes('condition')) {
				c = datas[key];
			}
		})
		return c;
	}

	setFormConfig = (config)=>{
		Object.keys(config).forEach(key=>{
			this[key] = config[key];
		})
		return this;
	}
}